package com.bawei.module_moto_circle.ui.search

import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.forEachIndexed
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.dp
import com.bawei.lib_common.flow_eventbus.SelectPostTopicEvent
import com.bawei.lib_common.flow_eventbus.post.postEvent
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.sp
import com.bawei.module_moto_circle.R
import com.bawei.module_moto_circle.databinding.ActivitySearchBinding
import com.bawei.module_moto_circle.model.Topic
import com.bawei.myclub.base.mvvm.view.BaseToolbarActivity
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import dagger.hilt.android.AndroidEntryPoint

@Route(path = Router.Ui.SearchActivity)
@AndroidEntryPoint
class SearchActivity : BaseToolbarActivity<SearchViewModel, ActivitySearchBinding>() {
    @Autowired(name = "search_type")
    lateinit var mSearchType: String

    override val mLayoutResId: Int
        get() = R.layout.activity_search

    private val mSearchSuggestionsFragment by lazy {
        SearchSuggestionsFragment.newInstance(mOnlyTopic)
    }

    override val mViewModel: SearchViewModel by viewModels()

    private var mOnlyTopic = false

    override fun initView() {
        super.initView()
        showSoftKeyBoard(mBinding.etSearch)
        mOnlyTopic = mSearchType == "topic"
        supportFragmentManager.beginTransaction()
            .add(R.id.l_container, mSearchSuggestionsFragment, SearchSuggestionsFragment.TAG)
            .hide(mSearchSuggestionsFragment)
            .commitAllowingStateLoss()
    }

    override fun initData() {
        mBinding.viewModel = mViewModel
        //获取热门搜索
        mViewModel.hotTopics()
        //搜索
        mViewModel.searchKeywordList()
    }

    override fun initListener() {
        //清除所有记录
        mBinding.tvClear.setOnClickListener {

        }
        //取消
        mBinding.btnCancel.setOnClickListener {
            dismissKeyboard()
            finish()
        }
        //热门话题
        mViewModel.requestHotTopicsEvent.observeWithLifecycle(this) {
            when (it) {
                is Success -> {
                    if (mOnlyTopic) onShowSearchTopics() else onShowSearchAll()
                }

                else -> {

                }
            }
        }
        //搜索
        mViewModel.mSearchSuggestionEvent.observeWithLifecycle(this){
            when(it){
                is Loading ->{
                    mSearchSuggestionsFragment.onLoading()
                }
                is Success->{
                    mSearchSuggestionsFragment.onSuccess(mViewModel.mKeywords.value)
                    mSearchSuggestionsFragment.setNewData(mViewModel.mSuggestionList)
                }
                is Failed -> {
                    if (it.message == "暂无数据内容") {
                        mSearchSuggestionsFragment.clearData()
                    }
                    mSearchSuggestionsFragment.onError(it.message)
                }
                else -> {

                }
            }
        }
        //搜索列表显示
        mViewModel.mKeywords.observeWithLifecycle(this){
            if (it.trim().isEmpty()){
                if (mSearchSuggestionsFragment.isVisible)
                    hideSuggestion()
            } else {
                if (!mSearchSuggestionsFragment.isVisible) {
                    showSuggestion()
                }

            }
        }
    }

    //搜索所有页面的状态
    private fun onShowSearchAll() {
        mBinding.run {
            lSearchHistory.visibility = if (mViewModel.isHistoryEmpty()) View.GONE else View.VISIBLE
            if (mViewModel.mHotTopics.isEmpty()) {
                lHotTopic.visibility = View.GONE
            } else {
                mViewModel.mHotTopics.forEach {
                    lHotTopic.visibility = View.VISIBLE
                    val topicView = createFlowItem(it, true)
                    flowHotTopic.addView(topicView)
                    topicView.setOnClickListener{}
                }
            }
            lHotPost.visibility = View.GONE
            lHotArticle.visibility = View.GONE
            lHotInfo.visibility = View.GONE
            etSearch.hint = getString(com.bawei.lib_common.R.string.string_input_keywords)

        }
    }

    private fun onShowSearchTopics() {
        mBinding.run {
            lSearchHistory.visibility = View.GONE
            lHotTopic.visibility = if (mViewModel.mHotTopics.isEmpty()) View.GONE else View.VISIBLE
            mViewModel.mHotTopics.forEach {
                mBinding.flowHotTopic.addView(createFlowItem(it, true))
            }
            flowHotTopic.forEachIndexed { index, view ->
                view.setOnClickListener {
                    postEvent(
                        SelectPostTopicEvent(
                            mViewModel.mHotTopics[index].topicName,
                            mViewModel.mHotTopics[index].topicId.toString()
                        )
                    )
                    finish()
                }
            }
            lHotPost.visibility = View.GONE
            lHotArticle.visibility = View.GONE
            lHotInfo.visibility = View.GONE
            etSearch.hint = getString(com.bawei.lib_common.R.string.string_input_topic)
        }
    }

    private val mTextColorResId by lazy {
        val typedValue = TypedValue()
        this.theme.resolveAttribute(com.bawei.lib_common.R.attr.colorText, typedValue, true)
        typedValue.resourceId
    }
    private fun createFlowItem(item: Topic, isTopic: Boolean = false): TextView {
        val textView = TextView(this)
        textView.includeFontPadding = true
        if (isTopic) {
            textView.text = "#${item.topicName}#"
        } else {
            textView.text = item.topicName
        }
        textView.setTextColor(ContextCompat.getColor(this, mTextColorResId))
        textView.paint.textSize = 14f.sp
        textView.maxWidth = 251.dp
        textView.tag = item
        textView.maxLines = 1
        textView.ellipsize = TextUtils.TruncateAt.END
        textView.setBackgroundResource(R.drawable.shape_search_history_tab_4dp)


        return textView
    }

    private fun showSuggestion() {
        supportFragmentManager.beginTransaction().show(mSearchSuggestionsFragment).commitAllowingStateLoss()
    }

    private fun hideSuggestion() {

        supportFragmentManager.beginTransaction().hide(mSearchSuggestionsFragment).commitAllowingStateLoss()

    }
}